package com.ch.android.lookforkotlinv2.adapter

import android.widget.ImageView
import androidx.core.net.toUri
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.ch.android.lookforkotlinv2.R
import com.ch.android.networklib.ApiService

/**
 * Author: conghao
 * Date: 2024/1/23 9:24
 * Description: MyBindingAdapter
 */

object MyBindingAdapter {
    @JvmStatic
    @BindingAdapter("imgUrl", "imgHolder", "imgError", requireAll = false)
    fun setImageUrl(imageView: ImageView, src: String?, holder: Int?, error: Int?) {
        // 用于替换图片的域名
        var replacedSrc: String? = null
        src?.let {
            try {
                // Uri.host: 域名
                // Uri.port: 端口号
                // Uri.authority: 域名 + 端口号
                val authority = it.toUri().authority
                if (authority != null) {
                    val newAuthority = ApiService.BASE_URL.toUri().authority
                    if (newAuthority != null && newAuthority != authority ) {
                        replacedSrc = it.replace(authority, newAuthority)
                    }
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        Glide.with(imageView)
            .load(replacedSrc ?: src)
            .placeholder(holder ?: R.drawable.cover1)
            .error(error ?: R.drawable.cover2)
            .into(imageView)
    }

}
